from rest_framework import serializers
from .models import User
from django_redis import get_redis_connection
import logging

log = logging.getLogger('django')

import re


class UserModelSerializer(serializers.ModelSerializer):
    sms_code = serializers.CharField(max_length=6, min_length=4, write_only=True, help_text='短信验证码')
    token = serializers.CharField(max_length=1000, read_only=True, help_text="token令牌")

    class Meta:
        model = User
        fields = ['mobile', 'password', 'sms_code','token','id','username']
        extra_kwargs = {
            "mobile":{"write_only":True,},
            "password": {"write_only": True,},
            "id":{"read_only": True,},
            "username":{"read_only":True}
        }

    def validate(self, attrs):
        mobile = attrs.get('mobile')
        if not re.match("^1[3-9]\d{9}$", mobile):
            return serializers.ValidationError('对不起,手机号码格式不正确')
        try:
            User.objects.get(mobile=mobile)
            return serializers.ValidationError('对不起,手机号码格式不正确')
        except User.DoesNotExist:
            pass
        sms_code = attrs.get("sms_code")
        redis_conn = get_redis_connection("sms_code")
        code_bytes = redis_conn.get("sms_%s" % mobile)
        if not code_bytes and code_bytes.decode() == sms_code:
            return serializers.ValidationError('验证码过期或错误')
        redis_conn.delete("sms_%s" % mobile)
        return attrs

    def create(self, validated_data):

        del validated_data["sms_code"]
        # password = validated_data.get('password')
        # validated_data['password'] = User.set_password(password)
        try:
            validated_data["username"]=validated_data["mobile"]
            user = super().create(validated_data=validated_data)
            user.set_password(validated_data.get('password'))
            user.save()
        except:
            log.error("用户注册信息保存失败")
            return serializers.ValidationError('对不起,用户注册保存失败')

        from rest_framework_jwt.settings import api_settings

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        user.token = jwt_encode_handler(payload)


        return user